<!-- 出入院信息 门诊诊断 OutpatientDiagnosis -->
<template>
  <div class="page-center">
    <div class="medical-form">
      <el-form :model="formData" label-width="140px" class="info-form" label-position="left">
        <el-divider content-position="left">
          <h3>门诊诊断</h3>
        </el-divider>

        <el-row :gutter="12">
          <!-- 门诊诊断信息 -->
          <el-col :span="24">
            <el-card class="box-card" shadow="never">
              <div slot="header" class="clearfix">
                <span>诊断信息</span>
              </div>
              <el-form-item label="门诊诊断">
                <div class="display-value info-value">{{ display(formData.diagnosis) }}</div>
              </el-form-item>
              <el-form-item label="确诊日期">
                <div class="display-value info-value">{{ display(formData.dateTime) }}</div>
              </el-form-item>
              <el-form-item label="疾病编码">
                <div class="display-value info-value">{{ display(formData.diagnosisCode) }}</div>
              </el-form-item>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { outpatientDiagnosis } from '@/api/dataEntry/demographicInformation'

export default {
  name: 'OutpatientDiagnosis',
  data() {
    return {
      formData: {
        patientId: null,
        diagnosis: '',
        dateTime: '',
        diagnosisCode: ''
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters('patient', ['robustPatientId', 'patientFallbackData'])
  },
  watch: {
    robustPatientId: {
      handler(newId) {
        if (newId) {
          this.formData.patientId = newId
          this.loadData(newId)
        } else {
          this.resetForm()
        }
      },
      immediate: true
    }
  },
  async mounted() {
    // 如果当前没有患者信息，尝试从存储恢复
    if (!this.robustPatientId) {
      const restored = await this.restorePatientFromStorage()
      if (restored) {
        this.formData.patientId = restored.id || restored.patientId
        this.loadData(this.formData.patientId)
      }
    }
  },
  methods: {
    ...mapActions('patient', ['restorePatientFromStorage']),

    async loadData(patientId) {
      if (this.loading) return

      this.loading = true
      try {
        const res = await outpatientDiagnosis({ recordId: patientId })
        this.handleResponseData(res)
      } catch (error) {
        console.error('Failed to load outpatient diagnosis:', error)
        this.applyFallbackData()
      } finally {
        this.loading = false
      }
    },

    handleResponseData(res) {
      // 统一处理响应数据格式
      const payload = res?.data?.data ?? res?.data ?? res ?? {}

      this.formData.diagnosis = payload.diagnosis || ''
      this.formData.dateTime = this.formatDate(payload.dateTime) || ''
      this.formData.diagnosisCode = payload.diagnosisCode || ''
    },

    applyFallbackData() {
      const patient = this.patientFallbackData
      if (patient) {
        this.formData.diagnosis = patient.diagnosis || patient.outpatientDiagnosis || ''
        this.formData.dateTime = this.formatDate(patient.dateTime || patient.diagnosisDate) || ''
        this.formData.diagnosisCode = patient.diagnosisCode || patient.diseaseCode || ''
      }
    },

    formatDate(date) {
      if (!date) return ''
      if (typeof date === 'string') return date
      if (date instanceof Date) return date.toISOString().split('T')[0]
      return String(date)
    },

    resetForm() {
      this.formData = {
        patientId: null,
        diagnosis: '',
        dateTime: '',
        diagnosisCode: ''
      }
    },

    display(val) {
      if (val === null || val === undefined || String(val).trim() === '') return '-'
      return val
    }
  }
}
</script>

<!-- 引入共享样式 -->
<style src="@/styles/shared.css"></style>

<style scoped>
</style>
